using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using Microsoft.Win32;

using FreeFlow.Administration;
using FreeFlow.Administration.WinFormsControls;

namespace FreeFlowAdministrator
{
	/// <summary>
	/// Summary description for OptionsControl.
	/// </summary>
	public class OptionsControl : System.Windows.Forms.UserControl
	{
    private FreeFlowAdministrator.UIActionsControl uiActionsControl;
    private System.Windows.Forms.PictureBox pictureBox1;
    private System.Windows.Forms.TextBox urlTextBox;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.Label label3;
    private System.Windows.Forms.NumericUpDown queryTimeoutTextBox;
    private Label label4;
    private DataGridView clientUrlsGrid;
    private DataGridViewComboBoxColumn dsn;
    private DataGridViewTextBoxColumn url;
    private Label label5;
		/// <summary> 
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public OptionsControl()
		{
			// This call is required by the Windows.Forms Form Designer.
			InitializeComponent();

      UIActionList actionList = new UIActionList();
      actionList.Add("Apply changes", "Apply any changes made", new ActionExecuteDelegate(ApplyChanges));
      uiActionsControl.Actions = actionList;

      urlTextBox.Text = WebDllLocation("");
      queryTimeoutTextBox.Value = QueryTimeout();

      Hashtable datasources = DSN.DSNs;
      foreach (DictionaryEntry item in datasources)
      {
        dsn.Items.Add(item.Key);
      }

      // load web client specified URLs
      RegistryKey key = Registry.CurrentUser.OpenSubKey(Constants.RegistryKey);
      if (key != null)
      {
        RegistryKey subKey = key.OpenSubKey(webSubKey);
        if (subKey != null)
        {
          string[] valueNames = subKey.GetValueNames();
          for (int i = 0; i < valueNames.Length; i++)
          {
            string dsnName = valueNames[i];
            if (dsn.Items.Contains(dsnName))
            {
              int row = clientUrlsGrid.Rows.Add();
              clientUrlsGrid.Rows[row].Cells[0].Value = dsnName;
              clientUrlsGrid.Rows[row].Cells[1].Value = subKey.GetValue(valueNames[i]);
            }
          }
        }
      }
		}

    private Server server;
    public void LoadForServer(Server server)
    {
      this.server = server;
    }

    private const string timeoutRegKey = "QueryTimeout";
    public static int QueryTimeout()
    {
      int timeout = 15;
      RegistryKey key = Registry.CurrentUser.OpenSubKey(Constants.RegistryKey);
      if (key != null)
        if (key.GetValue(timeoutRegKey) != null)
          timeout = Convert.ToInt32(key.GetValue(timeoutRegKey));
      return timeout;
    }

    private const string webRegKey = "WebDllLocation";
    private const string webSubKey = "ClientDsns";
    public static string WebDllLocation(string dsn)
    {
      string webDllLocation = "http://localhost/Metastorm";

      RegistryKey key = Registry.CurrentUser.OpenSubKey(Constants.RegistryKey);
      if (key != null)
      {
        // get the default URL
        if (key.GetValue(webRegKey) != null)
          webDllLocation = key.GetValue(webRegKey).ToString();

        // see if there is a specific URL
        RegistryKey subKey = key.OpenSubKey(webSubKey);
        if (subKey != null)
        {
          string[] valueNames = subKey.GetValueNames();
          for (int i = 0; i < valueNames.Length; i++)
          {
            if (valueNames[i] == dsn)
            {
              webDllLocation = subKey.GetValue(valueNames[i]).ToString();
              break;
            }
          }
        }
      }

      return webDllLocation;
    }

		/// <summary> 
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Component Designer generated code
		/// <summary> 
		/// Required method for Designer support - do not modify 
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
      System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(OptionsControl));
      this.pictureBox1 = new System.Windows.Forms.PictureBox();
      this.urlTextBox = new System.Windows.Forms.TextBox();
      this.label1 = new System.Windows.Forms.Label();
      this.label2 = new System.Windows.Forms.Label();
      this.queryTimeoutTextBox = new System.Windows.Forms.NumericUpDown();
      this.label3 = new System.Windows.Forms.Label();
      this.label4 = new System.Windows.Forms.Label();
      this.clientUrlsGrid = new System.Windows.Forms.DataGridView();
      this.dsn = new System.Windows.Forms.DataGridViewComboBoxColumn();
      this.url = new System.Windows.Forms.DataGridViewTextBoxColumn();
      this.uiActionsControl = new FreeFlowAdministrator.UIActionsControl();
      this.label5 = new System.Windows.Forms.Label();
      ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
      ((System.ComponentModel.ISupportInitialize)(this.queryTimeoutTextBox)).BeginInit();
      ((System.ComponentModel.ISupportInitialize)(this.clientUrlsGrid)).BeginInit();
      this.SuspendLayout();
      // 
      // pictureBox1
      // 
      this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
      this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
      this.pictureBox1.Location = new System.Drawing.Point(556, 8);
      this.pictureBox1.Name = "pictureBox1";
      this.pictureBox1.Size = new System.Drawing.Size(32, 32);
      this.pictureBox1.TabIndex = 1;
      this.pictureBox1.TabStop = false;
      // 
      // urlTextBox
      // 
      this.urlTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                  | System.Windows.Forms.AnchorStyles.Right)));
      this.urlTextBox.Location = new System.Drawing.Point(8, 70);
      this.urlTextBox.Name = "urlTextBox";
      this.urlTextBox.Size = new System.Drawing.Size(540, 20);
      this.urlTextBox.TabIndex = 5;
      this.urlTextBox.Text = "urlTextBox";
      // 
      // label1
      // 
      this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                  | System.Windows.Forms.AnchorStyles.Right)));
      this.label1.Location = new System.Drawing.Point(8, 16);
      this.label1.Name = "label1";
      this.label1.Size = new System.Drawing.Size(540, 40);
      this.label1.TabIndex = 4;
      this.label1.Text = "Web client location (e.g http://localhost/Metastorm). This URL will be used when " +
          "opening folders in the web client. It will only work in version 7 and later";
      // 
      // label2
      // 
      this.label2.Location = new System.Drawing.Point(11, 273);
      this.label2.Name = "label2";
      this.label2.Size = new System.Drawing.Size(80, 16);
      this.label2.TabIndex = 6;
      this.label2.Text = "Query timeout:";
      // 
      // queryTimeoutTextBox
      // 
      this.queryTimeoutTextBox.Location = new System.Drawing.Point(91, 271);
      this.queryTimeoutTextBox.Maximum = new decimal(new int[] {
            10000,
            0,
            0,
            0});
      this.queryTimeoutTextBox.Name = "queryTimeoutTextBox";
      this.queryTimeoutTextBox.Size = new System.Drawing.Size(56, 20);
      this.queryTimeoutTextBox.TabIndex = 7;
      // 
      // label3
      // 
      this.label3.Location = new System.Drawing.Point(147, 273);
      this.label3.Name = "label3";
      this.label3.Size = new System.Drawing.Size(48, 14);
      this.label3.TabIndex = 8;
      this.label3.Text = "seconds";
      // 
      // label4
      // 
      this.label4.AutoSize = true;
      this.label4.Location = new System.Drawing.Point(8, 51);
      this.label4.Name = "label4";
      this.label4.Size = new System.Drawing.Size(393, 13);
      this.label4.TabIndex = 9;
      this.label4.Text = "Default URL (used when no specific URL for the current DSN has been specified)";
      // 
      // clientUrlsGrid
      // 
      this.clientUrlsGrid.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                  | System.Windows.Forms.AnchorStyles.Right)));
      this.clientUrlsGrid.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
      this.clientUrlsGrid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
      this.clientUrlsGrid.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.dsn,
            this.url});
      this.clientUrlsGrid.Location = new System.Drawing.Point(8, 115);
      this.clientUrlsGrid.Name = "clientUrlsGrid";
      this.clientUrlsGrid.Size = new System.Drawing.Size(540, 150);
      this.clientUrlsGrid.TabIndex = 10;
      // 
      // dsn
      // 
      this.dsn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
      this.dsn.HeaderText = "DSN";
      this.dsn.Name = "dsn";
      this.dsn.Resizable = System.Windows.Forms.DataGridViewTriState.True;
      this.dsn.Sorted = true;
      this.dsn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
      // 
      // url
      // 
      this.url.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
      this.url.HeaderText = "Web client URL";
      this.url.Name = "url";
      // 
      // uiActionsControl
      // 
      this.uiActionsControl.Actions = null;
      this.uiActionsControl.Dock = System.Windows.Forms.DockStyle.Right;
      this.uiActionsControl.Location = new System.Drawing.Point(598, 0);
      this.uiActionsControl.Name = "uiActionsControl";
      this.uiActionsControl.Size = new System.Drawing.Size(150, 408);
      this.uiActionsControl.TabIndex = 0;
      // 
      // label5
      // 
      this.label5.AutoSize = true;
      this.label5.Location = new System.Drawing.Point(8, 96);
      this.label5.Name = "label5";
      this.label5.Size = new System.Drawing.Size(145, 13);
      this.label5.TabIndex = 11;
      this.label5.Text = "URLs used for specific DSNs";
      // 
      // OptionsControl
      // 
      this.Controls.Add(this.label5);
      this.Controls.Add(this.clientUrlsGrid);
      this.Controls.Add(this.label4);
      this.Controls.Add(this.label3);
      this.Controls.Add(this.queryTimeoutTextBox);
      this.Controls.Add(this.label2);
      this.Controls.Add(this.urlTextBox);
      this.Controls.Add(this.label1);
      this.Controls.Add(this.pictureBox1);
      this.Controls.Add(this.uiActionsControl);
      this.Name = "OptionsControl";
      this.Size = new System.Drawing.Size(748, 408);
      ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
      ((System.ComponentModel.ISupportInitialize)(this.queryTimeoutTextBox)).EndInit();
      ((System.ComponentModel.ISupportInitialize)(this.clientUrlsGrid)).EndInit();
      this.ResumeLayout(false);
      this.PerformLayout();

    }
		#endregion

    private string ApplyChanges()
    {
      // set default web client URL
      RegistryKey key = Registry.CurrentUser.CreateSubKey(Constants.RegistryKey);
      key.SetValue(webRegKey, urlTextBox.Text);

      // set DSN specific web client URLs
      string[] subKeys = key.GetSubKeyNames();
      if (Array.IndexOf(subKeys, webSubKey) > -1)
        key.DeleteSubKeyTree(webSubKey);
      RegistryKey dsns = key.CreateSubKey(webSubKey);
      for (int i = 0; i < clientUrlsGrid.RowCount; i++)
      {
        if (clientUrlsGrid.Rows[i].Cells[0].Value != null)
        {
          dsns.SetValue(clientUrlsGrid.Rows[i].Cells[0].Value.ToString(),
            clientUrlsGrid.Rows[i].Cells[1].Value.ToString());
        }
      }

      // query timeouts
      key.SetValue(timeoutRegKey, Convert.ToInt32(queryTimeoutTextBox.Value));
      if (server != null)
        server.QueryTimeout = Convert.ToInt32(queryTimeoutTextBox.Value);
      return Constants.ChangesApplied;
    }
	}
}
